/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.pc;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者和消费者问题:
 * <p>
 * 多线程操作资源类时会出现混乱的现象：那么这个问题改则呢么解决呢？
 * 使用Lock类进行加锁操作
 */
public class C {

    public static void main(String[] args) {

        Lock lock = new ReentrantLock();

        Ticket3 ticket = new Ticket3();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                //加锁
                lock.lock();
                try {
                    ticket.sale();
                } catch (Exception exception) {
                    exception.printStackTrace();
                } finally {
                    lock.unlock(); //释放锁
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lock.lock();
                try {
                    ticket.sale();
                } catch (Exception exception) {
                    exception.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lock.lock();
                try {
                    ticket.sale();
                } catch (Exception exception) {
                    exception.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "C").start();
    }

}


/**
 * 线程操作资源类
 * <p>
 * 属性、方法
 */
class Ticket3 {

    private int num = 30;

    /**
     * ReentrantLock: 可重入锁；默认的是不公平锁；通过改变参数可以让其变成公平锁ReentrantLock(true)
     */


    public void  sale() {
        if (num != 0) {
            System.out.println(Thread.currentThread().getName() + "卖出票为:" + num-- + "剩余票:" + num);
        }
    }
}
